<template>
  <div>
    <van-nav-bar title="搜索" left-arrow @click-left="$router.go(-1)" />
    <van-search
      v-model="keyword"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @input="onInput"
      shape="round"
    >
      <template #action>
        <div @click="onSearch">
          搜索
        </div>
      </template>
    </van-search>
    <van-cell-group>
      <van-cell
        v-for="(item, index) in showList"
        :key="index"
        icon="search"
        @click="
          $router.push({
            path: '/searchres',
            query: { keyword: suggestList[index] }
          })
        "
      >
        <!-- 原来放title的地方放具名插槽 -->
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell-group>
      <van-cell title="历史记录"> </van-cell>
      <van-cell
        :title="history[index]"
        v-for="(item, index) in history"
        :key="index"
      >
        <template #right-icon>
          <van-icon name="close" class="close-icon" @click="delClick()" />
        </template>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestList, getHistory, delHistory } from './home.js'
export default {
  name: 'search',
  data () {
    return {
      keyword: '',
      suggestList: [],
      history: [],
      //定时器ID
      timeId: null
    }
  },
  methods: {
    onSearch () {
      this.$router.push({
        path: '/searchres',
        query: { keyword: this.keyword }
      })
    },
    onInput () {
      clearTimeout(this.timeId)
      //添加防抖
      this.timeId = setTimeout(async () => {
        if (this.keyword == '') {
          this.suggestList = []
          return
        }
        let res = await getSuggestList(this.keyword)
        console.log(res)
        this.suggestList = res.data.data.options
      }, 500)
    },
    async delClick () {
      let res = await delHistory()
      console.log(res)
    }
  },
  computed: {
    showList () {
      let reg = new RegExp(this.keyword, 'gi')
      return this.suggestList.map(v =>
        v.replace(reg, match => `<span style="color:red">${match}</span>`)
      )
      //match：匹配到的字符串，每匹配成功一次都会执行后面回调函数
      // return this.suggestList.map(v => {
      //   return v.replace(reg, match => {
      //     return `<span style="color:red">${match}</span>`
      //   })
      // })
    }
  },
  async created () {
    let res = await getHistory()
    console.log(res)
    this.history = res.data.data.keywords
  }
}
</script>

<style lang="less"></style>
